"""
Use python-icalendar to format and write events. These can be sent by mail etc
"""
from tg import config
import os
ical_storage_dir = config.get('ical_storage_dir')
if not ical_storage_dir:
    ical_storage_dir = os.environ['TMPDIR']
if not os.path.isdir(ical_storage_dir):
    raise StandardError, "the specified ical_storage_dir %s does not exist"%ical_storage_dir
elif not os.access(ical_storage_dir,os.W_OK):
    raise StandardError, "no write permission for ical_storage_dir %s"%ical_storage_dir
from icalendar import Calendar,Event
from datetime import datetime
now = datetime.utcnow()
from icalendar import UTC # timezone
from random import random

class iCalExport:

    def __init__(self):
        self.cal = Calendar()
        self.cal.add('prodid', '-//Lifepyscle//lifepyscle.foxhall.de//')
        self.cal.add('version', '0.1')
        self.location = None

    def addEvent(self,start=now,end=now,stamp=now,summary=None,uid=None,priority=None):
        self.event = Event()
        if not summary:
            self.event.add('summary',u'No summary was provided for this event')
        else:
            self.event.add('summary',u'%s'%summary)
        if not uid:
            # 20050115T101010/27346262376@mxm.dk
            pre = datetime.strftime(start,"%Y%m%dT%H%M%S")
            post = str(random())[2:] # 13 char rand
            self.event['uid'] = "%s/%s@lifepyscle.foxhall.de"%(pre,post)
        else:
            self.event['uid'] = uid
        self.event.add('dtstart',start)
        self.event.add('dtend',end)
        self.event.add('dtstamp',stamp)
        self.cal.add_component(self.event)

    def writeToFile(self,location=None):
        """ if no absolute location passed then write to the standard storage directory """
        if not location: # use the event uid
            self.location = os.path.abspath(os.path.join(ical_storage_dir,"%s.ical"%self.event['uid'].replace("/","_"))) # replace slash in filename with underscore
            fd = open(self.location,'wb')
            fd.write(self.cal.as_string())
            fd.close()
        else:
            raise StandardError, "not implemented"
        return self.location

    def returnString(self):
        """ if the icalendar should be returned as a string in memory, use this method """
        pass

